package kuberneteshelper

import (
	"context"
	"fmt"
	"strings"

	"v8s-controller/internal/k8s"

	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/client-go/kubernetes/scheme"
)

func createResources(client *k8s.Repository, bytes []byte) {
	ctx := context.Background()

	nonSplit := string(bytes)
	resources := make([]runtime.Object, 0)

	datas := strings.Split(nonSplit, "---")
	for _, data := range datas {
		if data != "" {
			current := convert([]byte(data))
			resources = append(resources, current)
		}
	}

	describable, err := k8s.ToDescribableResources(resources)
	if err != nil {
		panic(err)
	}

	byNamespace := map[string][]runtime.Object{}
	for _, resource := range describable {
		namespace := resource.Namespace()
		slice, exists := byNamespace[namespace]
		if !exists {
			slice = make([]runtime.Object, 0)
		}

		byNamespace[namespace] = append(slice, resource.Resource())
	}

	for _, slice := range byNamespace {
		if err := client.CreateResources(ctx, slice); err != nil {
			panic(err)
		}
	}
}

func convert(data []byte) runtime.Object {
	object, _, err := scheme.Codecs.UniversalDeserializer().Decode(data, nil, nil)
	if err != nil {
		panic(fmt.Errorf("cannot deserialize '%s': %w", data, err))
	}

	return object
}
